package com.saoft.jcms.web.controller;

import com.saoft.jcms.entity.Admin;
import com.saoft.jcms.service.AdminService;
import com.saoft.jcms.web.dto.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Controller
public class LoginController {

    @Autowired
    AdminService adminService;

    @GetMapping("login")
    public String login(){
        return "login";
    }

    /**
     * 退出功能
     * @param request
     * @return
     */
    @GetMapping("logout")
    public String logout(HttpServletRequest request) {
        request.getSession().setAttribute("loginUser", null);
        return "redirect:/";
    }

    @ResponseBody
    @PostMapping("login")
    public ResponseDTO loginPost(HttpServletRequest request,
                                 String username, String password){

        Admin admin = adminService.getByUsername(username);
        if (admin == null) {
            return ResponseDTO.error();
        }else{
            String password1 = admin.getPassword();
            if (password1 != null && password.equals(admin.getPassword())) {
                request.getSession().setAttribute("loginUser",admin);
                return ResponseDTO.success();
            }
        }
        return ResponseDTO.error();
    }
}
